package com.linkage.jz.bankruptcy.activity.Msg;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingIntrActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.adapter.ChatAdapter;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.Msg;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MsgDetailActivity extends BaseActivity implements OnClickListener {

    private List<Msg> mMsgs;
    private ShapeLoadingDialog shapeLoadingDialog ;
    private ChatAdapter mAdapter;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TextView top_title,tv_title,tv_content;
    Button top_back,top_mune;

    RecyclerView mRvChatList;
    EditText mEtContent;
    Button mBtSend;
    String fromUserId;

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            addMsg(new Msg(null, "来数据了！", Msg.TYPE_BLE, df.format(new Date())));
            handler.postDelayed(this, 5000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_msg_detail);

        Intent intent = getIntent();
        fromUserId = intent.getStringExtra("fromUserId");
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        initView();
        initTitle();
        mMsgs = new ArrayList<Msg>();
//        mMsgs = mMsgDaoUtil.queryAllMsg();

//        Msg msg1 = new Msg(1l, "来数据了1来数据了1来数据了1来数据了1来数据了1来数据了1来数据了1来数据了1！", Msg.TYPE_BLE, df.format(new Date()));
//
//        mMsgs.add(msg1);
//        Msg msg2 = new Msg(1l, "来数据了2！来数据了1来数据了1来数据了1来数据了1来数据了1来数据了1来数据了1来数据了1", Msg.TYPE_PHONE, df.format(new Date()));
//
//        mMsgs.add(msg2);
//        Msg msg3 = new Msg(1l, "来数据了3！", Msg.TYPE_BLE, df.format(new Date()));
//
//        mMsgs.add(msg3);
//        Msg msg4 = new Msg(1l, "来数据了4！", Msg.TYPE_PHONE, df.format(new Date()));
//
//        mMsgs.add(msg4);
//
//        Msg msg5 = new Msg(1l, "来数据了4！", Msg.TYPE_PHONE, df.format(new Date()));
//
//        mMsgs.add(msg5);
//
//        Msg msg6 = new Msg(1l, "来数据了4！", Msg.TYPE_PHONE, df.format(new Date()));
//
//        mMsgs.add(msg6);
//
//        Msg msg7 = new Msg(1l, "来数据了4！", Msg.TYPE_PHONE, df.format(new Date()));
//
//        mMsgs.add(msg7);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRvChatList = findViewById(R.id.rv_chatList);
        mBtSend = findViewById(R.id.bt_send);
        mEtContent = findViewById(R.id.et_content);
        mRvChatList.setLayoutManager(linearLayoutManager);
//        mAdapter = new ChatAdapter(this, mMsgs);
        mRvChatList.setAdapter(mAdapter);
        mRvChatList.scrollToPosition(mAdapter.getItemCount() - 1);

//        mMsgDaoUtil.setUpdateListener(new OnDbUpdateListener() {
//            @Override
//            public void onUpdate(Msg msg) {
//                mAdapter.addItem(msg);
//                mRvChatList.scrollToPosition(mAdapter.getItemCount() - 1);
//            }
//        });

        mRvChatList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < -10) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mEtContent.getWindowToken(), 0);
                }
            }
        });

        handler.postDelayed(runnable, 5000);
        getData();
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        top_back.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("消息详情");
        top_mune.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initView() {
        top_title = findViewById(R.id.top_title);
        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);
    }

    private boolean addMsg(Msg msg) {
//        boolean flag = mMsgDaoUtil.insertMsg(msg);
//        return flag;
        return true;
    }


    public void onViewClicked() {
        String content = mEtContent.getText().toString();
        addMsg(new Msg(null, content, Msg.TYPE_PHONE, df.format(new Date())));
        mEtContent.setText("");
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;


            default:
                break;
        }
    }

    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        final String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        final String verName = Utils.getLocalVersionName(this)+"";
        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)

                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("sendUserId", userId)
                .add("pageNumber", "1")
                .add("pageSize", "100")
                .add("fromUserId", fromUserId)


                .build();

        String url = Consts.WEBURL_CHATLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                  runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI


                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
               shapeLoadingDialog.dismiss();

                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    JSONObject data = object.optJSONObject("data");

                    if(object.optInt("code") == 0)
                    {
                        JSONArray ary = data.optJSONArray("list");

                        for(int i=0;i<ary.length();i++)
                        {
                            JSONObject info = (JSONObject) ary.get(i);
                            Msg msg1 = new Msg();
                            msg1.set_id(i);
                            msg1.setContent(info.optString("note"));
                            String sendUserId = info.optString("sendUserId");
                            if(sendUserId.equalsIgnoreCase(userId))
                            {
                                msg1.setType(Msg.TYPE_PHONE);
                            }else{
                                msg1.setType(Msg.TYPE_BLE);
                             }

                            String time = info.optString("readTime");
                            long l_time = Long.parseLong(time)*1000;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            Date dateOld = new Date(l_time); // 根据long类型的毫秒数生命一个date类型的时间
                            String strTime = sdf.format(dateOld);
                            msg1.setTime(strTime);
                            mMsgs.add(msg1);
                        }
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                               mAdapter.notifyDataSetChanged();
                            }

                        });

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(MsgDetailActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(MsgDetailActivity.this, "获取失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
